package com.miaoshaproject.controller;

import com.alibaba.druid.util.StringUtils;
import com.miaoshaproject.controller.viewobject.UserVO;
import com.miaoshaproject.error.BussinessException;
import com.miaoshaproject.error.EmBussinessError;
import com.miaoshaproject.response.CommonReturnType;
import com.miaoshaproject.service.UserService;
import com.miaoshaproject.service.model.UserModel;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import sun.misc.BASE64Encoder;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;

/**
 * Created by kenny on 2019/1/5.
 */
@CrossOrigin(allowCredentials ="true",allowedHeaders = "*")
@Controller
@RequestMapping("/user")
public class UserController extends BaseController{

    @Autowired
    UserService userService;
    @Autowired
    private HttpServletRequest httpServletRequest;

    @RequestMapping("/get")
    @ResponseBody
    public CommonReturnType getUser(@RequestParam(name="id") int id) throws BussinessException {

        UserModel userModel = userService.getUserById(id);
        if(userModel==null){
            throw new BussinessException(EmBussinessError.USEER_NOT_EXIST);
        }

        return CommonReturnType.create(convertFromModel(userModel));
    }
    @RequestMapping(value="/login",method = {RequestMethod.POST},consumes = {CONTENT_TYPE_FROMED})
    @ResponseBody
    public CommonReturnType login(@RequestParam("telphone")String telphone,
                                  @RequestParam("password")String password) throws UnsupportedEncodingException, NoSuchAlgorithmException, BussinessException {

        if(org.apache.commons.lang3.StringUtils.isEmpty(telphone)||
                org.apache.commons.lang3.StringUtils.isEmpty(password)){
            throw  new BussinessException(EmBussinessError.PARAMETER_VALIDATION_ERROR);
        }
        UserModel model =userService.validateLogin(telphone,endodeByMd5(password));
        httpServletRequest.getSession().setAttribute("IS_LOGIN",true);
        httpServletRequest.getSession().setAttribute("LOGIN_USER",model);

        return CommonReturnType.create(null);

    }

    @RequestMapping(value="/register",method = {RequestMethod.POST},consumes = {CONTENT_TYPE_FROMED})
    @ResponseBody
    public CommonReturnType register(@RequestParam(name="telphone")String telphone,
                                     @RequestParam(name="otpCode")String otpCode,
                                     @RequestParam(name="name")String name,
                                     @RequestParam(name="age")Integer age,
                                     @RequestParam(name="gender")Integer gender,
                                     @RequestParam(name="password")String password) throws BussinessException, UnsupportedEncodingException, NoSuchAlgorithmException {
        System.out.print(httpServletRequest.isRequestedSessionIdFromCookie());
        String isSessionOtpCode = (String) httpServletRequest.getSession().getAttribute(telphone);
        if (!StringUtils.equals(otpCode, isSessionOtpCode)) {
            throw new BussinessException(EmBussinessError.PARAMETER_VALIDATION_ERROR, "短信验证码不对");
        }

        //用户注册
        UserModel userModel =new UserModel();
        userModel.setName(name);
        userModel.setAge(age);
        userModel.setTelephone(telphone);
        userModel.setGender(gender);
        userModel.setEncrptPassword(endodeByMd5(password));
        userModel.setRegisterMode("byphone");
        userService.register(userModel);
        return CommonReturnType.create(null);
    }
    @CrossOrigin
    @RequestMapping(value="/getOtp",method = {RequestMethod.POST},consumes = {CONTENT_TYPE_FROMED})
    @ResponseBody
    public CommonReturnType getOtp(@RequestParam(name="telphone",required=false)String telphone){
        Random random = new Random();
        int randomint = random.nextInt(99999);
        randomint+=10000;
        String otpCode = String.valueOf(randomint);
        System.out.print(httpServletRequest.isRequestedSessionIdFromCookie());
        httpServletRequest.getSession().setAttribute(telphone, otpCode);

        System.out.print("telphone==="+ telphone +" & otp====="+ otpCode);

        return CommonReturnType.create(null);


    }


    public String endodeByMd5(String str) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        MessageDigest messageDigest = MessageDigest.getInstance("MD5");
        BASE64Encoder base64Encoder = new BASE64Encoder();
        String newstr= base64Encoder.encode(messageDigest.digest(str.getBytes("utf-8")));
        return newstr;
    }
    public UserVO convertFromModel(UserModel userModel){
        UserVO userVO = new UserVO();

        BeanUtils.copyProperties(userModel,userVO);

        return userVO;

    }


}
